<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>登录页面</title>
</head>
<body>
    <h1>注册</h1>
    <form id="registerForm">
        <label>用户名：
            <input type="text" name="username" id="username" required>
        </label><br>
        <label>密码：
            <input type="password" name="password" id="password" required>
        </label><br>
        <label>确认密码：
            <input type="password" name="password2" id="password2" required>
        </label><br>
        <button type="submit">注册</button><br>
    </form>
    <script>
        document.getElementById('registerForm').addEventListener('submit', function(event) {
            event.preventDefault();
            const username = document.getElementById("username").value;
            const password = document.getElementById("password").value;
            const password2 = document.getElementById("password2").value;
            
            if (!username || !password || !password2) {
                alert("所有字段都必须填写");
                return;
            }
            
            if (password !== password2) {
                alert("两次输入的密码不一致，请检查");
                return;
            }
            
            fetch('/register', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: new URLSearchParams({
                    username: username,
                    password: password
                })
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('注册失败');
                }
                return response.text();
            })
            .then(message => {
                alert(message);
                document.getElementById('registerForm').reset(); // 重置表单
            })
            .catch(error => {
                alert(error.message);
            });
        });
    </script>
</body>
</html>